package com.yunxi.service.localService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.web.DictConstant;
import com.yunxi.dao.sto.StoVehicleLendOrderMapper;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.StoStockInPlan;
import com.yunxi.model.sto.StoStockOutPlan;
import com.yunxi.model.sto.StoVehicleLendOrder;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.service.localService.sat.SatMessService;
import com.yunxi.service.localService.sto.*;
import com.yunxi.sto.pojo.*;
import com.yunxi.sto.service.StoStockInPlanDubboService;
import com.yunxi.sto.service.StoStockOutPlanDubboService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借车单 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-30
 */
@Service
public class StoVehicleLendOrderServiceImpl extends ServiceImplPlus<StoVehicleLendOrderMapper, StoVehicleLendOrder> implements StoVehicleLendOrderService {

    @Autowired
    @Qualifier(value = "stoStockOutPlanDubboServiceImpl")
    StoStockOutPlanDubboService stoStockOutPlanDubboService;

    @Autowired
    @Qualifier(value = "stoStockInPlanDubboServiceImpl")
    StoStockInPlanDubboService stoStockInPlanDubboService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;

    @Autowired
    @Qualifier(value = "stoStockOutPlanServiceImpl")
    StoStockOutPlanService stoStockOutPlanService;

    @Autowired
    @Qualifier(value = "stoStockInPlanServiceImpl")
    StoStockInPlanService stoStockInPlanService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "vehiclePdiBillServiceImpl")
    VehiclePdiBillService vehiclePdiBillService;

    /**
     * 作废/恢复
     * @param list
     * @param isDel
     * @throws Exception
     */
    @Override
    public void delAndReset(List<String> list, Integer isDel,String userId) throws Exception {
        if(list != null && list.size() > 0){
            for(String id : list){
                ////作废,校验只能作废车辆未出库的单据
                StoVehicleLendOrder stoVehicleLendOrder = baseMapper.selectById(id);
                if(stoVehicleLendOrder != null){
                    Integer orderState = stoVehicleLendOrder.getOrderState();
                    if(isDel.equals(1)){
                        if(orderState != null && !orderState.equals(1)){
                            throw new Exception("操作失败,只能作废车辆未出库的单据!");
                        }
                        else{
                            stoVehicleLendOrder.setOrderState(5);
                        }
                    }
                    else if(isDel.equals(0)){
                        if(orderState != null && !orderState.equals(5)){
                            throw new Exception("操作失败,只能恢复作废的单据!");
                        }
                        else{
                            stoVehicleLendOrder.setOrderState(1);
                        }
                    }
                    stoVehicleLendOrder.setUpdateBy(userId);
                    baseMapper.updateById(stoVehicleLendOrder);
                    QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("VIN",stoVehicleLendOrder.getVin());
                    VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
                    if(vehicleOffline != null){
                        if(isDel.equals(1)){
                            vehicleOffline.setVehicleIsFrozen(0);
                            vehicleOffline.setFrozenReasonKey(null);
                            vehicleOffline.setIsLock(0);
                        }
                        else if(isDel.equals(0)){
                            Integer vehicleIsFrozen = vehicleOffline.getVehicleIsFrozen();
                            if(vehicleIsFrozen.equals(1))throw new Exception("操作失败,VIN码:"+stoVehicleLendOrder.getVin()+"已冻结,无法恢复该借车单!");
                            vehicleOffline.setVehicleIsFrozen(1);
                        }
                        vehicleOfflineService.saveOrUpdate(vehicleOffline);
                    }
                    //同时作废/恢复新增时生成的出入库计划
                    delAndResetStockInOut(isDel, stoVehicleLendOrder,userId);
                }
                else {
                    throw new Exception("操作失败,无法根据主键id;"+id+"找到对应单据!");
                }
            }
        }
    }

    /**
     * 同时作废/恢复新增时生成的出入库计划
     * @param isDel
     * @param stoVehicleLendOrder
     */
    private void delAndResetStockInOut(Integer isDel, StoVehicleLendOrder stoVehicleLendOrder,String userId) throws Exception{
        QueryWrapper<StoStockOutPlan> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN",stoVehicleLendOrder.getVin());
        queryWrapper.ne("BILL_STATE","6");//排除已完成的
        Integer vehiclePurpose = stoVehicleLendOrder.getVehiclePurpose();//车辆用途
        if(vehiclePurpose != null && vehiclePurpose.equals(1)){
            queryWrapper.eq("STOCK_OUT_TYPE","4");//借车出库
        }
        else if(vehiclePurpose != null && vehiclePurpose.equals(2)){
            queryWrapper.eq("STOCK_OUT_TYPE","13");//消耗领用
        }
        StoStockOutPlan stoStockOutPlan = stoStockOutPlanService.getOne(queryWrapper);
        if(stoStockOutPlan != null){
            List<String> arrayList = new ArrayList();
            arrayList.add(stoStockOutPlan.getStockOutPlanId());
            stoStockOutPlanDubboService.delAndReset(arrayList,1,userId);
        }

        //是否需要归还,是则有入库计划
        Integer isNeedReturn = stoVehicleLendOrder.getIsNeedReturn();
        if(isNeedReturn != null && isNeedReturn.equals(1)){
            QueryWrapper<StoStockInPlan> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("VIN",stoVehicleLendOrder.getVin());
            queryWrapper1.ne("BILL_STATE","2");
            if(vehiclePurpose != null && vehiclePurpose.equals(1)){
                queryWrapper1.eq("STOCK_IN_TYPE","6");//借车入库
            }
            else if (vehiclePurpose != null && vehiclePurpose.equals(2)){
                queryWrapper1.eq("STOCK_IN_TYPE","14");//消耗领用
            }
            StoStockInPlan stoStockInPlan = stoStockInPlanService.getOne(queryWrapper1);
            if(stoStockInPlan != null){
                List<String> arrayList = new ArrayList();
                arrayList.add(stoStockInPlan.getStockInPlanId());
                stoStockInPlanDubboService.delAndReset(arrayList,isDel,userId);
            }
        }
    }

    /**
     * 转出入库计划
     * @param stoVehicleLendOrderVO
     * @param isOut
     * @throws Exception
     */
    @Override
    public void toInOutPlan(StoVehicleLendOrderVO stoVehicleLendOrderVO, Integer isOut) throws Exception {
        String vin = stoVehicleLendOrderVO.getVin();
        Integer vehiclePurpose = stoVehicleLendOrderVO.getVehiclePurpose();//车辆用途
        //根据VIN查询库位
        QueryWrapper<PmsVehicleStock> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN", vin);
        PmsVehicleStock pmsVehicleStock = vehicleStockMService.getOne(queryWrapper);
        //转出库
        if (isOut.equals(1)) {
            StoStockOutPlanVO stoStockOutPlanVO = new StoStockOutPlanVO();
            if(vehiclePurpose != null && vehiclePurpose.equals(1)){
                stoStockOutPlanVO.setStockOutType("4");//借车出库
            }
            else if (vehiclePurpose != null && vehiclePurpose.equals(2)){
                stoStockOutPlanVO.setStockOutType("13");//消耗领用
            }
            stoStockOutPlanVO.setPlanStockOutDate(new Date());
            if (pmsVehicleStock != null) {
                stoStockOutPlanVO.setStorageCode(pmsVehicleStock.getStorageLocation());
            }
            stoStockOutPlanVO.setVin(vin);
            stoStockOutPlanVO.setPlanStockOutDate(stoVehicleLendOrderVO.getLendTime());//计划出库时间

            //分配司机
            Date date = new Date();
            SimpleDateFormat dd = new SimpleDateFormat("dd");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String day = dd.format(date);
            String format = simpleDateFormat.format(date);
            StoDriverVO stoDriverVO1 = new StoDriverVO();
            stoDriverVO1.setWorkMonth(format);
            stoDriverVO1.setDay(Integer.parseInt(day));
            List<StoDriverVO> list = vehiclePdiBillService.queryTodayDriver(stoDriverVO1);
            if(list != null && list.size() > 0){
//                StoDriverVO stoDriverVO =list.get(0);
//                stoStockOutPlanVO.setStockOutDriver(stoDriverVO.getRfid());
//                stoStockOutPlanVO.setRfidDate(new Date());
//                //推送消息给司机
//                SatMessAddVO satMessAddVO = new SatMessAddVO();
//                satMessAddVO.setType("出库");
//                satMessAddVO.setInfo("有一个新的出库计划!");
//                satMessAddVO.setSalesConsultantNo(stoDriverVO.getUserCode());
//                satMessAddVO.setReceiveRoleCode(DictConstant.USER_ROLE_DRIVER);
//                satMessService.pdaNewMess(satMessAddVO);
                for(StoDriverVO vo : list){
                    String workDays = vo.getWorkDays();
                    if(StringUtils.isNotEmpty(workDays)){
                        String[] split = workDays.split(",");
                        Boolean isContains = false;
                        for(String workDay : split){
                            if(Integer.valueOf(workDay).equals(Integer.valueOf(day))){
                                isContains = true;
                                break;
                            }
                        }
                        if(isContains){
                            stoStockOutPlanVO.setStockOutDriver(vo.getRfid());
                            stoStockOutPlanVO.setRfidDate(new Date());

                            //推送消息给司机
                            SatMessAddVO satMessAddVO = new SatMessAddVO();
                            satMessAddVO.setType("出库");
                            satMessAddVO.setInfo("有一个新的出库计划!");
                            satMessAddVO.setSalesConsultantNo(vo.getUserCode());
                            satMessAddVO.setReceiveRoleCode(DictConstant.USER_ROLE_DRIVER);
                            satMessService.pdaNewMess(satMessAddVO);
                        }
                    }
                }
            }

            //生成出库计划
            stoStockOutPlanDubboService.saveOrUpdate(stoStockOutPlanVO);

        }
        //转入库
        else if (isOut.equals(0)) {
            StoStockInPlanVO stoStockInPlanVO = new StoStockInPlanVO();
            if(vehiclePurpose != null && vehiclePurpose.equals(1)){
                stoStockInPlanVO.setStockInType("6");//借车入库
            }
            else if (vehiclePurpose != null && vehiclePurpose.equals(2)){
                stoStockInPlanVO.setStockInType("14");//消耗领用
            }
            Date date = stoVehicleLendOrderVO.getReturnTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(date);
            stoStockInPlanVO.setVin(vin);
            stoStockInPlanVO.setPlanStockInDate(format);//计划入库时间
            //生成入库计划
            stoStockInPlanDubboService.saveAndUpdate(stoStockInPlanVO);
        }
    }

    /**
     * 查询超期未还车的借车单
     * @return
     * @throws Exception
     */
    @Override
    public List<StoVehicleLendOrder> queryOverTimeLendOrder(){
        List<StoVehicleLendOrder> list = baseMapper.queryOverTimeLendOrder();
        return list;
    }

    @Override
    public List<StoVehicleLendOrderQueryVO> export(StoVehicleLendOrderQueryVO stoVehicleLendOrderQueryVO) throws Exception {
        Map map = BeanTools.bean2map(stoVehicleLendOrderQueryVO);
        return baseMapper.queryByList(map);
    }

    /**
     * 查询借车详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public StoVehicleLendOrderDetailVO loadDetail(String id) throws Exception {
        return baseMapper.loadDetail(id);
    }
}
